<template>
	<div class="com-container">
		<!--对话-->
		<scroll-view scroll-y="true" :scroll-top="scrollTop" class="message-container">
			<!-- <div class="message-self" v-for="item in messages">
				
				<div v-if="item.type==='ai'" class="ai-head">
					<wd-icon name="chat" color="#fff" size="22px"></wd-icon>
				</div>
				<div v-if="item.type==='ai'" class="ai-message">
					{{ item.content }}
				</div>
				<div style="flex: 1;">
					
				</div>
				
				<div v-if="item.type === 'usr'" class="usr-message">
					{{ item.content }}
				</div>
				<div v-if="item.type === 'usr'" class="usr-head">
					<wd-icon name="user-circle" color="#fff" size="22px"></wd-icon>
				</div>
			</div> -->

			<div class="message-self" v-for="item in messages">
				<!--ai-->
				<div v-if="item.type === 'ai'" class="ai-head">
					<wd-icon name="chat" color="#fff" size="22px"></wd-icon>
				</div>
				<div v-if="item.type === 'ai'" class="ai-message">
					{{ isRef(item.content) ? item.content.value : item.content }}
					<view style="margin-top: 10rpx; z-index: 99999">
						<!-- 新增按钮：智能巩固 -->
						<button v-if="item.msgShowButton" size="default" @click="testTap"
							style="backgroundColor:#332a86; color:#ffffff">去做题</button>
					</view>
				</div>
				<div style="flex: 1;"></div>
				<!--用户-->
				<div v-if="item.type === 'usr' && item.content.charAt(0) !== '$'" class="usr-message">
					{{ item.content }}
				</div>
				<div v-if="item.type === 'usr' && item.content.charAt(0) !== '$'" class="usr-head">
					<wd-icon name="user-circle" color="#fff" size="22px"></wd-icon>
				</div>
			</div>

		</scroll-view>

		<!-- 样例prompt -->
		<view class="example-prompt" v-if="promptShow">
			<view class="component" @click="promptClick(1)">
				<view class="example-title">今日计划</view>
				<view class="example-self">{{ prompt1Text }}</view>
			</view>
			<view class="component" @click="promptClick(2)"> 
				<view class="example-title">错题巩固</view>
				<view class="example-self">{{ prompt2Text }}</view>
			</view>
			<view class="component" @click="promptClick(3)">
				<view class="example-title">薄弱点分析</view>
				<view class="example-self">{{ prompt3Text }}</view>
			</view>
			<view class="component" @click="promptClick(4)">
				<view class="example-title">习题推荐</view>
				<view class="example-self">{{ prompt4Text }}</view>
			</view>
		</view>

		<!--输入-->
		<div class="input-container">
			<textarea maxlength="-1" class="input-inner" v-model="textSubmit" auto-height />
			<div class="btn" v-if="!showLoading" @click="submitButtonClick">
				<wd-icon name="chat" color="#fff" size="22px"></wd-icon>
			</div>
			<div class="btn" v-else>
				<wd-loading type="outline" size="22px" color="#0f0c3a" />
			</div>
		</div>
	</div>
</template>

<script setup>
	import { ref, defineProps, defineEmits, isRef, onMounted } from 'vue';
	import { chatRouterPages, chatRouterTabs, tabsLinks } from '@/js/chatRouter.js'
	import { globalProps } from '../js/global';
	import { onLoad, onUnload, onHide } from '@dcloudio/uni-app'
	
	// 给用户预制的4个prompt是否显示
	const promptShow = ref(false)
	const prompt1Text = ref('请你给我一个今天的学习计划')
	const prompt2Text = ref('我想巩固下错题')
	const prompt3Text = ref('请分析下我的薄弱点')
	const prompt4Text = ref('请根据我的学习情况给我推荐一些习题')
	const promptClick = (index) => {
		switch (index) {
			case 1:
				textSubmit.value = prompt1Text.value
				break
			case 2:
				textSubmit.value = prompt2Text.value
				break
			case 3:
				textSubmit.value = prompt3Text.value
				break
			case 4:
				textSubmit.value = prompt4Text.value
				break
		}
		submitButtonClick()
		promptShow.value = false
	}

	onHide(()=>{
		uni.$off('chatAccept')
		console.log('AI对话监听请求关闭')
	})
	
	onMounted(()=>{
		//AI对话监听
		console.log('AI对话监听请求开启')
		uni.$on('chatAccept',(value)=>{
			console.log(value)
			textSubmit.value = value
			submitButtonClick()
		})
		//
		if(props.homepagePrompt){
			promptShow.value = true
		}
		uni.connectSocket({
			url: 'ws://aitalk.yym-free.com?userId='+ globalProps.userInfo.userId +'&questionId=2',
			// url: 'ws://192.168.149.190:8765?userId='+ globalProps.userInfo.userId +'&questionId=2',
		});
		uni.onSocketOpen(function (res) {
		  console.log('WebSocket连接已打开！');
		});
	})

	const props = defineProps({
		quesId: Number,
		homepagePrompt: {
			type: Boolean,
			default: false
		}
	})

	const emit = defineEmits(['readReply', 'onlyRead', 'onlyStop'])
	const textSubmit = ref('')
	const aiMessageContent = ref('');
	const responsing = ref(false)
	
	//scroll-div scroll bottom
	const scrollTop = ref(0)
	const scrollToBottom = ()=>{
		scrollTop.value += 50
	}
	
	const quesContent = ref('')
	const replaying = ref(true)
	const messages = ref([])
	
	// messages去ref如果需要传给后端
	// const convertMessagesToPlain = () => {
	// 	return messages.value.map(msg => {
	// 		const { type, content } = msg;
	// 		return {
	// 			type,
	// 			content: isRef(content) ? content.value : content
	// 		}
	// 	})
	// }

	//收到ws信息
	uni.onSocketMessage(function (res) {
		console.log('收到服务器内容：' , res);
		addAiMsg(res)
	});
	
	//增加用户消息
	const addUsrMsg = ()=>{
		uni.sendSocketMessage({
		  data: textSubmit.value
		});
		messages.value.push({
			type: 'usr',
			content: textSubmit.value
		})
		textSubmit.value = ''
		scrollToBottom()
	}
	
	const waitingForJump = ref(false)
	const showLoading = ref(false)

	// 接收7410信息
	const showButton = ref(false)

	//增加ai消息
	const addAiMsg = (res)=>{
		// April 14th 新增逻辑：显示按钮
		if (!responsing.value) {
			// 判断第一次接收的消息是否为"7410"，如果是则显示按钮
			if (res.data === '7410') {
				console.log('收到7410')
				messages.value.push({
					type: 'ai',
					content: '',
					msgShowButton: false
				})
				showButton.value = true
				responsing.value = true
				// 向父页面发送事件，开始读
				emit('onlyRead')
				return
			}
		}
		// end 新增逻辑：显示按钮

		// 新增逻辑：跳转页面
		if(!responsing.value){
			// 判断第一次接收的消息是否为"12138"，如果是则等待跳转
			if(res.data === '12138'){
				waitingForJump.value = true
				return
			}
		}
		
		if(waitingForJump.value){
			let jumpLink = '/' + res.data
			waitingForJump.value = false
			showLoading.value = false
			messages.value.push({
				type: 'ai',
				content: '好的，为你打开新页面！'
			})
			scrollToBottom()
			setTimeout(()=>{
				// 尝试switchTab，如果错误则redirectTo
				if(tabsLinks.includes(jumpLink)){
					uni.switchTab({
						url: jumpLink
					})
				}else{
					uni.navigateTo({
						url: jumpLink
					})
				}
				
			}, 500)
			return
		}
		// end 新增逻辑：跳转页面
		
		//发送后第一次收到回应
		if(!responsing.value){
			messages.value.push({
				type: 'ai',
				content: ''
			})
			responsing.value = true
			emit('onlyRead')
			return
		}
		//最后一次回应
		if(res.data === 'None'){
			responsing.value = false
			emit('onlyStop')
			showLoading.value = false
			// 如果7410，则显示按钮
			if(showButton.value){
				messages.value[messages.value.length - 1].msgShowButton = true;
				showButton.value = false
			}
		}
		else{
			//过程中
			messages.value[messages.value.length - 1].content +=res.data
		}
		scrollToBottom()
	}
	
	const testTap = () => {
		console.log('点击了按钮')
		// 跳转到错题巩固页面
		getAllRedoThenJump()
	}

	// 获取所有错题并跳转到遗忘曲线页面
	const getAllRedoThenJump = () => {
		console.log('获取所有错题并跳转到遗忘曲线页面')
		let getUrl = globalProps.baseApi + 'cuotiji/cuotiForRedo/?userID=' + globalProps.userInfo.id
		uni.request({
			url: getUrl,
			method: 'GET',
			success: (res) => {
				console.log('成功生成练习：', res.data)
				uni.setStorageSync('exerciseList', res.data);
				allRedoJump()
			},
			fail: (err) => {
				uni.showToast({
					title: '生成练习失败',
					icon: 'none'
				})
				console.log(err)
			}
		})

	}

	// 跳转到遗忘曲线页面
	const allRedoJump = () => {
		uni.navigateTo({
			url: '/pages/AIConsolidation/QuestionShowPage',
			// 将题目数组作为参数传递给ExerciseDetailPage页面
			success: (res) => {
				console.log('跳转成功', res);
				if (res.errMsg === 'navigateTo:ok') {
					// 传递参数
					// uni.setStorageSync('exerciseList', this.exerciseList);
				}
			}
		});
	}
	const submitButtonClick = () => {
		if (textSubmit.value) {
			showLoading.value = true
			addUsrMsg()
		}
	/*
	let aiContent;
	if (textSubmit.value) {
		messages.value.push({
			type: 'usr',
			content: textSubmit.value
		})
	
		const command = textSubmit.value.toLowerCase().trim();
	
		// 查找命令是否在chatRouterPages中
		const pageRoute = chatRouterPages[command];
		if (pageRoute) {
			// 如果找到对应的路由，使用uni.navigateTo跳转到该页面
			aiContent = '中嘞哥，已为您跳转到' + pageRoute + '页面';
			// getAudioUrl(aiContent);
			emit('readReply', aiContent)
			messages.value.push({
				type: 'ai',
				content: aiContent
			})
			uni.navigateTo({
				url: pageRoute
			});
		} else {
			// 查找命令是否在chatRouterTabs中
			const tabRoute = chatRouterTabs[command];
			if (tabRoute) {
				// 如果找到对应的tab，使用uni.switchTab跳转到该tab页面
				aiContent = '中嘞哥，已为您切换到' + tabRoute + '页面';
				// getAudioUrl(aiContent); // 更改为触发事件
				emit('readReply', aiContent)
				messages.value.push({
					type: 'ai',
					content: aiContent
				})
				uni.switchTab({
					url: tabRoute
				});
			} else {
				console.log("submit text: " + textSubmit.value);
				// 暂时读用户输入的文本，有待改成从后端获取gpt返回的文本消息
				// getAudioUrl(textSubmit.value); // 更改为触发事件
				emit('readReply', textSubmit.value)
				// messages.value.push({
				// 	type: 'ai',
				// 	content: 'gpt返回的文本消息'
				// })
				const newAiMessage = {
					type: 'ai',
					content: ref('')
				}
				messages.value.push(newAiMessage);
	
				let index = 0;
				const textReceiveFromGpt = 'gpt返回的文本消息gpt返回的文本消息gpt返回的文本消息gpt返回的文本消息gpt返回的文本消息gpt返回的文本消息';
				const addCharWithDelay = () => {
					if (index < textReceiveFromGpt.length) {
						newAiMessage.content.value += textReceiveFromGpt[index];
						index++;
						// 生成0到200毫秒之间的随机数作为延时时间
						const randomDelay = Math.random() * 200;
						setTimeout(addCharWithDelay, randomDelay);
					}
				}
	
				addCharWithDelay();
			}
		}
		textSubmit.value = ''; 
	} */
}
</script>

<script>
	//参考
	//建立websocket
	/* const ws = ref('')
	const startWebSocket=()=>{
	  try {
	    ws.value = new WebSocket(websocketUrl+userId.value);
	    ws.value.onmessage = getMessage
	    ws.value.onerror = onError
	  }catch (e){
	    message.error('与服务器建立websocket对话失败，'+e)
	  }
	}
	const onError = ()=>{
	  message.error('websocket连接出错，请重新选择对话')
	}
	//收到消息
	const getMessage = (msg)=>{
	  var messageDetail = JSON.parse(msg.data)
	  messageDetail.sendTime = timeCorrect(messageDetail.sendTime)
	  allMessages.value.push(messageDetail)
	
	  nextTick(()=>{
	    scrollContainer.value.scrollTo({
	      top: scrollContainer.value.scrollHeight,
	      behavior: 'smooth',
	    });
	  })
	}
	//发送消息
	const sendMessage = ()=>{
	  if (ws.value && ws.value.readyState === WebSocket.OPEN){
	    try {
	      ws.value.send(JSON.stringify({
	        messageId: dialogueId.value,
	        toUserId: otherId.value,
	        messageContent: inputText.value,
	        messageImg: fileUrl.value
	      }))
	      inputText.value = ''
	      fileList.value = []
	      fileUrl.value = ''
	    }catch (e){
	      message.error('发送失败，'+e)
	    }
	  }else{
	    message.error('发送失败，请先选择会话')
	  }
	}
	
	onUnmounted(()=>{
	  if (ws.value && ws.value.readyState === WebSocket.OPEN) {
	    ws.value.close();
	  }
	}) */
</script>

<style>
	.com-container{
		display: flex;
		flex-direction: column;
		align-items: center;
		height: 100%;
	}
	/*对话*/
	.message-container{
		flex: 1;
		width: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: start;
		overflow-y: scroll;
		overflow-x: hidden;
	}
	.message-self{
		width: 100%;
		height: auto;
		margin-bottom: 8px;
		display: flex;
		align-items: flex-start;
		justify-content: space-around;
	}
	.message-self .ai-head{
		width: 36px;
		height: 36px;
		background-color: #4942ad;
		border-radius: 8px;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.message-self .ai-message{
		max-width: calc(100% - 92px);
		margin: 4px 8px;
		color: #fff;
		background-color: #eee;
		color: #333;
		padding: 8px;
		border-top-right-radius: 8px;
		border-bottom-right-radius: 8px;
		border-bottom-left-radius: 8px;
		letter-spacing: 1px;
		white-space: pre-line;
	}
	.message-self .usr-message{
		max-width: calc(100% - 92px);
		margin: 4px 8px;
		color: #fff;
		background-color: #4942ad;
		padding: 8px;
		border-top-left-radius: 8px;
		border-bottom-right-radius: 8px;
		border-bottom-left-radius: 8px;
		letter-spacing: 1px;
		white-space: pre-line;
	}
	.message-self .usr-head{
		width: 36px;
		height: 36px;
		background-color: #4942ad;
		border-radius: 8px;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	/*输入*/
	.input-container{
		max-height: 80px;
		width: 100%;
		display: flex;
		align-items: flex-end;
		justify-content: space-between;
		position: relative;
	}
	.input-container .input-inner{
		color: black;
		background-color: #eee;
		max-height: 60px;
		height: auto;
		min-height: 24px;
		padding: 8px 8px 4px 8px;
		width: calc(100% - 76px);
		margin-top: 16px;
		border-radius: 4px;
	}
	.input-container .btn{
		width: 48px;
		height: 36px;
		background-color: #4942ad;
		border-radius: 8px;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	

	/* 底部 */
	.example-prompt {
		display: flex;
		flex-wrap: wrap;
		justify-content: center;
		animation: bottom-in-ani .8s 1;
	}

	.component {
		/* background: linear-gradient(to right bottom, #1c3364, #19035b); */
		background: linear-gradient(90deg, rgba(48,26,133,1) 0%, rgba(25,13,69,1) 100%);
		width: calc(100%);
		margin: 10px 0 0 0;
		padding: 10px;
		/* border: 1px solid #ccc; */
		border-radius: 10px;
	}

	.example-title {
		/* font-size: 18px; */
		font-weight: bold;
		margin-bottom: 5px;
	}

	.example-self {
		font-size: small;
		color: #aaa;
	}
</style>